#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Tool.hpp"
#include "InetAddr.hpp"
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "输入格式为：./tcpclient ip port" << std::endl;
        exit(USAGE_ERR);
    }

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    uint16_t port = std::stoi(argv[2]);
    std::string ip = argv[1];

    InetAddr server(ip, port);

    // 建立连接
    int n = connect(sockfd, server.Addr(), server.Getsize());
    if (n < 0)
    {
        std::cerr << "建立连接失败" << std::endl;
        exit(CONNECT_ERR);
    }

    while (true)
    {
        std::string line;
        std::cout << "please Enter@";
        std::getline(std::cin, line);

        write(sockfd, line.c_str(), line.size());

        char buffer[1024];
        ssize_t size = read(sockfd, buffer, sizeof(buffer) - 1);
        if (size > 0)
        {
            buffer[size] = 0;
            std::cout << "server echo# " << buffer << std::endl;
        }
    }
    close(sockfd);
    return 0;
}